import React from "react";
import { Navigate, Outlet, useLocation } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext";
import type { UserRole } from "../types/roles";
import { ROUTES } from "../constants/routes";

interface ProtectedRouteProps {
    allowedRoles: UserRole[];
}

const roleHome: Record<UserRole, string> = {
    patient: ROUTES.patient.dashboard,
    doctor: ROUTES.doctor.dashboard,
};

export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ allowedRoles }) => {
    const { user } = useAuth();
    const location = useLocation();

    if (!user) {
        return <Navigate to={ROUTES.login} replace state={{ from: location }} />;
    }

    if (!allowedRoles.includes(user.role)) {
        return <Navigate to={roleHome[user.role]} replace />;
    }

    return <Outlet />;
};


